/*
 * 拍照的客户端路径
 * 不要使用多层目录 CreateMuliteDirectory() 多级目录创建方法无效
 * 目前创建目录的方法 CreateDirectory() 只能创建最内层目录，外层目录不存在，将无法创建。
 * 尚未实现递归创建多级目录
 * @type String
 */
var PATH = "D:/FuneralPicture/";

//开始预览
function start_preview(fileType) {
    var cameraName;
    if (fileType === 1) {
        //文件摄像头
        cameraName = "S520";
    } else {
        //人物摄像头
        cameraName = "S520_2";
    }
    for (i = 0; i < ScanCtrl.GetDeviceCount(); i++) {
        if (cameraName === ScanCtrl.GetDevName(i)) {
            //设置当前摄像头
            ScanCtrl.SetCurDev(i);
            break;
        }
    }
    changeResolution();
    ScanCtrl.StartPreviewEx();
}

//修改分辨率
function changeResolution() {
    ScanCtrl.SetResolution($('#resolution_input').val());
}

/**
 * 拍照
 * @param {type} path
 * @param {type} num
 * @returns {String|@var;PATH|unresolved}
 */
function TakePic(path, num)
{
    if (typeof (path) === "undefined") {
        path = PATH;
    }
    var fileName = path + get_name() + ".jpg";
//    添加日期
//    ScanCtrl.EnableDateRecord(1);
    var flag = ScanCtrl.Scan(fileName);
    if (flag) {
        //拍照成功
        EThumbnails.AddToDisplay(fileName);
        return fileName;
    } else {
        //拍照失败，尝试创建文件夹后在拍照
        if (typeof (num) === "undefined" || num === 0) {
            createFolder(path);
            return TakePic(path, 1);
        } else {
            alert("拍摄失败！");
            return null;
        }
    }
}

/**
 * 创建目录,只能创建最内存目录，上级目录不存在本方法将报错
 * @param {type} path
 * @returns {undefined}
 */
function createFolder(path) {
    if (typeof (path) === "undefined") {
        ScanCtrl.CreateDirectory(PATH);
    } else {
        ScanCtrl.CreateDirectory(path);
    }
}

//删除文件夹下所有文件
function deleteFolder(path) {
    if (typeof (path) === "undefined") {
        ScanCtrl.DeleteFolder(PATH);
    } else {
        ScanCtrl.DeleteFolder(path);
    }
}

//获得第一个被选中文件的路径
function getSelPath() {
    for (var i = 0; i < EThumbnails.GetDisplayCount(); i++) {
        if (EThumbnails.IsChecked(i)) {
            return EThumbnails.GetFilePath(i);
        }
    }
    return null;
}

/*
 * 获得路径
 * 单个文件时返回该文件路径
 * 多个文件时必须至少选择一个，返回第一个被选择的路径
 */
function getPath() {
    var path = getSelPath();
    if (path !== null) {
        return path;
    } else if (EThumbnails.GetDisplayCount() === 1) {
        return EThumbnails.GetFilePath(0);
    }
    return null;
}

/**
 * 上传文件
 * @param {type} type 添加还是修改，修改话即使没有拍照也返回 true
 * @param {type} url
 * @param {type} id
 * @param {type} fileType
 * @returns {Boolean}
 */
function upload(type, url, id, fileType) {
    if (EThumbnails.GetDisplayCount() === 0) {
        if (type === "Modify") {
            return true;
        }
        alert("请先拍摄，再保存！");
        return false;
    }
    var path = getPath();
    if (path === null) {
        alert("请先选择一个照片，再保存！");
    } else {
        url = "http://" + url + "/Fle.fileUpload?Order=uploadFile&id=" + id
                + "&fileType=" + fileType;
        var isSuccess = ScanCtrl.UploadFileOfHTTP(url
                , path, "");
        if (isSuccess) {
            deleteFolder();
            return true;
        } else {
            alert('保存照片失败！');
        }
    }

    return false;
}

/*
 * 生成文件名
 */
function get_name() {
    var date = new Date();
    var yy = date.getFullYear().toString();
    var mm = (date.getMonth() + 1).toString();
    var dd = date.getDate().toString();
    var hh = date.getHours().toString();
    var nn = date.getMinutes().toString();
    var ss = date.getSeconds().toString();
    var mi = date.getMilliseconds().toString();
    var picName = yy + mm + dd + hh + nn + ss + mi;
    return picName;
}

/**
 * 20151202 新版
 * 
 */
var dev1;
var video1;

export function plugin() {
    return document.getElementById('view1');
}

function view() {
    return document.getElementById('view1');
}

function thumb() {
    return document.getElementById('thumb1');
}

function select() {
    return document.getElementById('resolution');
}

function addEvent(obj, name, func) {
    if (obj.attachEvent) {
        obj.attachEvent("on" + name, func);
    } else {
        obj.addEventListener(name, func, false);
    }
}

function OpenVideo() {
    CloseVideo();

    //1 表示仅支持YUY2 ，2 表示仅支持MJPG，3 表示两者均支持
    var subtype1 = (plugin().Device_GetSubtype(dev1) === 2 ? 2 : 1);
    var nResolution1 = select().selectedIndex;

    video1 = plugin().Device_CreateVideo(dev1, nResolution1, subtype1);
    if (video1) {
        view().View_SelectVideo(video1);
        view().View_SetText("打开视频中，请等待...", 0);
    }
}

function CloseVideo() {
    if (video1) {
        view().View_SetText("", 0);
        plugin().Video_Release(video1);
        video1 = null;
    }
}

//id设备索引 1文件摄像头 2任务摄像头
export function Load(id) {

    if (typeof (id) !== "undefined") {
        //设备接入和丢失
        //type设备类型， 1 表示视频设备， 2 表示音频设备
        //idx设备索引
        //dbt 1 表示设备到达， 2 表示设备丢失		
        addEvent(plugin(), 'DevChange', function (type, idx, dbt) {
            if (plugin().Global_GetEloamType(1, idx) !== id) {
                return;
            }

            if (1 !== type) {
                return;
            }

            if (1 === dbt) {
                dev1 = plugin().Global_CreateDevice(1, idx);
                if (dev1) {
                    var nResolution = plugin().Device_GetResolutionCount(dev1);
                    for (var i = 0; i < nResolution; i++) {
                        var width = plugin().Device_GetResolutionWidth(dev1, i);
                        var heigth = plugin().Device_GetResolutionHeight(dev1, i);
                        select().add(new Option(width.toString() + "*" + heigth.toString()));
                    }

                    var sel;
                    if (plugin().Global_GetEloamType(1, idx) === 1) {
                        sel = 2;
                        select().selectedIndex = sel;
                    } else {
                        sel = 0;
                    }

                    var subtype = (plugin().Device_GetSubtype(dev1) === 2 ? 2 : 1);
                    //1 表示仅支持YUY2 ，2 表示仅支持MJPG，3 表示两者均支持
                    video1 = plugin().Device_CreateVideo(dev1, sel, subtype);
                    if (video1) {
                        view().View_SelectVideo(video1);
                        view().View_SetText("打开视频中，请等待...", 0);
                    }
                }
            } else if (2 === dbt) {
                if (video1) {
                    view().View_SetText("", 0);
                    plugin().Video_Release(video1);
                    video1 = null;
                    plugin().Device_Release(dev1);
                    dev1 = null;

                    select().options.length = 0;
                }
            }
        });
        view().Global_SetWindowName("view");
        thumb().Global_SetWindowName("thumb");
        plugin().Global_InitDevs();
    } else {
        // alert('李少展把里面的内容注释了，有问题联系李少展');
        // view().Global_SetWindowName("view");
        // thumb().Global_SetWindowName("thumb");
        // plugin().Global_InitDevs();
        // plugin().Global_InitIdCard();
    }

}

export function Unload() {
    if (video1) {
        view().View_SetText("", 0);
        plugin().Video_Release(video1);
        video1 = null;
        plugin().Device_Release(dev1);
        dev1 = null;
    }

    plugin().Global_DeinitIdCard();
    plugin().Global_DeinitDevs();
}

function Scan(num) {
    var imgList = plugin().Video_CreateImageList(video1, 0, view().View_GetObject());
    if (imgList) {
        var b;
        var len = plugin().ImageList_GetCount(imgList);
        for (var i = 0; i < len; i++) {
            var img = plugin().ImageList_GetImage(imgList, i);
            var Name = PATH + get_name() + ".jpg";

            b = plugin().Image_Save(img, Name, 0);
            if (b) {
                view().View_PlayCaptureEffect();
                thumb().Thumbnail_Add(Name);
            } else {
                //拍照失败，尝试创建文件夹后在拍照
                if (typeof (num) === "undefined" || num === 0) {
                    createFolderNew(PATH);
                    return Scan(1);
                } else {
                    alert("拍摄失败！");
                    return null;
                }
            }
            plugin().Image_Release(img);
        }
        plugin().ImageList_Release(imgList);
        return b;
    }
}

//获得第一个被选中文件的路径
function getSelPathNew() {
    for (var i = 0; i < thumb().Thumbnail_GetCount(); i++) {
        if (thumb().Thumbnail_GetCheck(i)) {
            return thumb().Thumbnail_GetFileName(i);
        }
    }
    return null;
}

/*  * 获得路径
 * 单个文件时返回该文件路径
 * 多个文件时必须至少选择一个，返回第一个被选择的路径
 */
function getPathNew() {
    var path = getSelPathNew();
    if (path !== null) {
        return path;
    } else if (thumb().Thumbnail_GetCount() === 1) {
        return thumb().Thumbnail_GetFileName(0);
    }
    return null;
}

/**
 * 上传文件
 * @param {type} type 添加还是修改，修改话即使没有拍照也返回 true
 * @param {type} url
 * @param {type} id
 * @param {type} fileType
 * @returns {Boolean}
 */
function uploadNew(type, url, id, fileType) {
    if (thumb().Thumbnail_GetCount() === 0) {
        if (type === "Modify") {
            return true;
        }
        alert("请先拍摄，再保存！");
        return false;
    }
    var path = getPathNew();
    if (path === null) {
        alert("请先选择一个照片，再保存！");
    } else {
        url = "http://" + url + "/Fle.fileUpload?Order=uploadFileNew&id=" + id
                + "&fileType=" + fileType;
        url = plugin().Global_CreateHttp(url);
        if (url) {
            var isSuccess = plugin().Http_UploadImageFile(url, path, path);
            if (isSuccess) {
                deleteFile();
                plugin().Http_Release(url);
                return true;
            } else {
                alert('保存照片失败！');
            }
            plugin().Http_Release(url);
        } else {
            alert("设备初始化失败（url错误）");
        }
    }
    return false;
}

//创建文件夹
function createFolderNew(path) {
    if (typeof (path) === "undefined") {
        thumb().Global_CreateDir(PATH);
    } else {
        thumb().Global_CreateDir(path);
    }
}

//删除文件夹
function deleteFolderNew(path) {
    if (typeof (path) === "undefined") {
        thumb().Global_RemoveDir(PATH);
    } else {
        thumb().Global_RemoveDir(path);
    }
}

/**
 * 删除文件
 * @returns {undefined}
 */
function deleteFile() {
    for (var i = 0; i < thumb().Thumbnail_GetCount(); i++) {
        thumb().Global_DelFile(thumb().Thumbnail_GetFileName(i));
    }
}